<?php 
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Galleries;
use App\Models\Collections;
use DB;

class Votes extends Model {

	protected $table = 'votes';
        const UPDATED_AT = null; 
	protected $fillable = array('collection_id', 'collection_user_id', 'user_id', 'created_at');
        

        public function delvote($params){
            $vote=$this->where('collection_id',$params['collection_id'])->where('user_id',$params['user_id'])->first();
            if($vote){
                if($vote=$this->where('collection_id',$params['collection_id'])->where('user_id',$params['user_id'])->delete()){
                    return $vote;
                }else{
                    return false;
                }
            }
            return true;
        }
        
        public function saveGalleryVotesNum($user_id){
            $galleries_model = new Galleries();
            $collections_model = new Collections();
            $votes_num = $collections_model->where('user_id',$user_id)->where('addtoGallery','1')->sum('total_vote');
            $gallery_info = $galleries_model->getGallery($user_id);
            if($votes_num){
                if(!$gallery_info){
                    return false;
                }
                $gallery_info->votes_num = $votes_num;
                if(!$gallery_info->save()){
                    return false;
                }
            }
            return true;
        }
        
        public function getUnreadNum($user_id) {
            $num = $this->where('collection_user_id', $user_id)
                    ->where('is_read', '0')
                    ->count();
            return $num;
        }
        
        public function updateread($user_id){
            DB::beginTransaction();
            $result = $this->where('collection_user_id',$user_id)->update(['is_read'=>'1']);
            DB::commit();
            return $result;
        }
}